package com.example.demo.controller;

import com.example.demo.model.ResponseBodyMessage;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(User user, HttpServletRequest request){
        User user1 = userService.login(user);
        if(user1==null){
            log.info("用户名："+user.getUsername()+" 密码："+user.getPassword()+" 登陆失败！");
            return new ResponseBodyMessage<User>(-1,"登陆失败",null);
        }else {
            HttpSession session=request.getSession(true);
            session.setAttribute("user",user1);
            user1.setPassword("");
            return new ResponseBodyMessage<>(0,"登录成功",user1);

        }

    }

    @RequestMapping("/info")
    public ResponseBodyMessage<String> info(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        if(session==null){
            log.info("当前未有登录信息");
            return new ResponseBodyMessage<>(-1,"当前未有登录信息",null);
        }else{
            User user= (User)session.getAttribute("user");
            return new ResponseBodyMessage<>(0,"获取用户信息成功",user.getUsername());
        }
    }
}
